//
//  LoginViewController.m
//  OptimumCarCharge
//
//  Created by WTM on 16/11/23.
//  Copyright © 2016年 童巍. All rights reserved.
//

#import "LoginViewController.h"
#import "WTMNetworkTool.h"
#import "Tool.h"
#import "DownPullView.h"
#import "SVProgressHUD.h"
#import <AVFoundation/AVFoundation.h>
#import "RootViewController.h"
//#import "RegisterViewController.h"

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *logo;
@property (weak, nonatomic) IBOutlet UIImageView *head;
@property (weak, nonatomic) IBOutlet UIImageView *phoneCode;
@property (weak, nonatomic) IBOutlet UIImageView *carNo;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic)DownPullView *pullView;

@property (weak, nonatomic) IBOutlet UITextField *userAcoountTextField;
@property (weak, nonatomic) IBOutlet UITextField *secrectTextField;

@property (weak, nonatomic) IBOutlet UITextField *plateNumTextField;
@property (weak, nonatomic) IBOutlet UIView *viewOne;
@property (weak, nonatomic) IBOutlet UIView *viewTwo;
@property (weak, nonatomic) IBOutlet UIView *viewThree;
@property (weak, nonatomic) IBOutlet UIButton *scanButton;
//@property (weak, nonatomic) IBOutlet UIButton *changePassWordButton;
@property (weak, nonatomic) IBOutlet UIButton *fogetButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;


@property (nonatomic)NSInteger twominutes;
@end

@implementation LoginViewController

//点击登录
- (IBAction)loginAction:(id)sender {
    
    if (self.userAcoountTextField.text.length <= 0) {
        [Tool errorWithMsg:@"请输入手机号"];
        return;
    }
    
    if (self.secrectTextField.text.length <= 0){
        [Tool errorWithMsg:@"请输入密码"];
        return;
    }
    
    if (self.plateNumTextField.text.length <= 0) {
        [Tool errorWithMsg:@"请输入车牌号"];
        return;
    }
    
    if (![Tool valiMobile:self.userAcoountTextField.text]) {
        [Tool errorWithMsg:@"请输入正确的手机号"];
        return;
    }
    [self login];
    
}

- (void)login
{

    [SVProgressHUD showWithStatus:@"正在登录中"];
    NSString *plateNum = [NSString stringWithFormat:@"%@%@",self.pullView.label.text,self.plateNumTextField.text];
    NSDictionary * parameters = @{@"mobileNumber":self.userAcoountTextField.text,@"plateNumber":plateNum,@"password":[Tool md5:self.secrectTextField.text]};
    [[WTMNetworkTool sharedNetworkTool]requestWithUrlstring:@"app/user/login" method:@"POST" parameters:@{@"params":parameters} success:^(id  _Nullable responseObject) {
        NSDictionary *loginMsg = [responseObject mutableCopy];
        NSLog(@"loginMsg %@",loginMsg);
        if ([[loginMsg objectForKey:@"status"] integerValue] == 0) {
            //登录成功
//            if ([[NSUserDefaults standardUserDefaults]objectForKey:@"token"]) {
//            NSDictionary *parameters = @{@"params":@{@"registerId":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"],@"platform":@"getui"}};
//            [[WTMNetworkTool sharedNetworkTool]requestWithUrlstring:@"app/user/submitRegisterId" method:@"POST" parameters:parameters success:nil failure:nil];
                [[NSUserDefaults standardUserDefaults]setValue:self.userAcoountTextField.text forKey:@"USER_ACOOUNT"];
                [[NSUserDefaults standardUserDefaults]setValue:[plateNum uppercaseString] forKey:@"PLANTE_Num"];
            [[NSUserDefaults standardUserDefaults]setValue:@1 forKey:@"ISLOGIN"];
            [[NSUserDefaults standardUserDefaults]setValue:[[[loginMsg objectForKey:@"result"]objectForKey:@"userinfo"]objectForKey:@"userName"]forKey:@"userName"];
            NSString * string = [[loginMsg objectForKey:@"result"]objectForKey:@"vehicle"];
            NSData *vehicleDate = [string dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *vehicleDic = [NSJSONSerialization JSONObjectWithData:vehicleDate options:0 error:nil];
            [[NSUserDefaults standardUserDefaults]setValue:[vehicleDic objectForKey:@"stationName"]forKey:@"stationName"];
                [[NSUserDefaults standardUserDefaults]synchronize];
                [SVProgressHUD dismiss];
                UIViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"mainNavi"];
                [UIApplication sharedApplication].keyWindow.rootViewController = viewController;
                [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
            
               
//            }
        }else{
                [SVProgressHUD dismiss];
                //登录失败
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"%@",[loginMsg objectForKey:@"resultMsg"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
        }
    } failure:^(NSError * _Nonnull error) {
         [SVProgressHUD dismiss];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"%ld",error.code] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
    }];


}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self addCAGradient];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    for (NSHTTPCookie *cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie: cookie];
    }
    [self.view removeConstraints:[self.view constraints]];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    DownPullView *pullView = [DownPullView initWithDownPullImage:@"downPull" frame:CGRectZero dataSource:@[@"粤",@"澳",@"川",@"鄂",@"赣",@"桂",@"贵",@"甘",@"港",@"沪",@"黑", @"京",@"津",@"冀",@"晋",@"吉",@"鲁",@"辽",@"闽", @"蒙",@"宁",@"青",@"琼",@"陕",@"苏",@"台",@"皖",@"湘",@"新",@"豫",@"云",@"渝",@"浙",@"藏"] showRows:3];
    self.pullView = pullView;
    [self.viewThree addSubview:pullView];
    [pullView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.viewThree.mas_centerY);
        make.height.mas_equalTo(kHeightOfPt(80));
        make.left.mas_equalTo(self.viewThree.mas_left).offset(kWidthOfPt(150));
        make.width.mas_equalTo(kWidthOfPt(120));
    }];
    
    
    [self initUI];
}


#pragma keyboardnotification
- (void)keyBoardWillShow:(NSNotification *)notification
{
        CGRect rect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
        CGFloat duration=[[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];
        NSInteger type=[[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey]integerValue];
        CGFloat difference = (self.viewThree.frame.origin.y + self.viewThree.frame.size.height) - (kScreenHeight - rect.size.height);
        if (difference > 0) {
            [UIView animateKeyframesWithDuration:duration delay:0 options:type animations:^{
                CGRect frame = self.view.frame;
                frame.origin.y = - difference;
                self.view.frame = frame;
            } completion:nil];
        }
}
- (void)keyBoardWillHide:(NSNotification *)notification
{
    CGFloat duration=[[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    NSInteger type=[[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey]integerValue];
    [UIView animateKeyframesWithDuration:duration delay:0 options:type animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = 0.0f;
        self.view.frame = frame;
    } completion:nil];

}


- (void)initUI{
    
    [self.logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.view.mas_top).offset(kHeightOfPt(110));
        make.height.mas_equalTo(kHeightOfPt(537));
        make.width.mas_equalTo(kWidthOfPt(780));
    }];
    
    [self.viewOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kWidthOfPt(820));
        make.height.mas_equalTo(kHeightOfPt(120));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.view.mas_top).offset(kHeightOfPt(110 + 537 + 200));
    }];
    self.viewOne.layer.cornerRadius = kHeightOfPt(60);
    self.viewOne.layer.borderColor = [UIColor colorWithHexString:@"#7ca3d6"].CGColor;
    self.viewOne.layer.borderWidth = 1;

    [self.viewTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kWidthOfPt(820));
        make.height.mas_equalTo(kHeightOfPt(120));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.view.mas_top).offset(kHeightOfPt(110 + 537 + 200 + 170));
    }];
    self.viewTwo.layer.cornerRadius = kHeightOfPt(60);
    self.viewTwo.layer.borderColor = [UIColor colorWithHexString:@"#7ca3d6"].CGColor;
    self.viewTwo.layer.borderWidth = 1;
    
    [self.viewThree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kWidthOfPt(820));
        make.height.mas_equalTo(kHeightOfPt(120));
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.view.mas_top).offset(kHeightOfPt(110 + 537 + 200 + 170 + 170));
    }];
    self.viewThree.layer.cornerRadius = kHeightOfPt(60);
    self.viewThree.layer.borderColor = [UIColor colorWithHexString:@"#7ca3d6"].CGColor;
    self.viewThree.layer.borderWidth = 1;


    [self.head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.viewOne.mas_left).offset(kWidthOfPt(50));
        make.centerY.mas_equalTo(self.viewOne.mas_centerY);
        make.width.mas_equalTo(kWidthOfPt(60));
        make.height.mas_equalTo(kHeightOfPt(60));
    }];
    
    [self.phoneCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.viewTwo.mas_left).offset(kWidthOfPt(50));
        make.centerY.mas_equalTo(self.viewTwo.mas_centerY);
        make.width.mas_equalTo(kWidthOfPt(60));
        make.height.mas_equalTo(kHeightOfPt(60));
    }];
    
    [self.carNo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.viewThree.mas_left).offset(kWidthOfPt(50));
        make.centerY.mas_equalTo(self.viewThree.mas_centerY);
        make.width.mas_equalTo(kWidthOfPt(60));
        make.height.mas_equalTo(kHeightOfPt(60));

        
    }];
    
    [self.userAcoountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.viewOne.mas_centerY);
        make.height.mas_equalTo(kHeightOfPt(80));
        make.left.mas_equalTo(self.viewOne.mas_left).offset(kWidthOfPt(30 + 80 + 40));
        make.right.mas_equalTo(self.viewOne.mas_right).offset(- kWidthOfPt(60));
    }];
    self.userAcoountTextField.font = systemFontOfPX(40);
    NSAttributedString *userPlaceHolder = [[NSAttributedString alloc]initWithString:@"请输入手机号" attributes:@{NSFontAttributeName :systemFontOfPX(40),NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#bfcfe5"]}];
    self.userAcoountTextField.attributedPlaceholder = userPlaceHolder;
    
    [self.secrectTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.viewTwo.mas_centerY);
        make.height.mas_equalTo(kHeightOfPt(80));
        make.left.mas_equalTo(self.viewTwo.mas_left).offset(kWidthOfPt(30 + 80 + 40));
        make.right.mas_equalTo(self.viewTwo.mas_right).offset(- kWidthOfPt(60));
    }];
    self.secrectTextField.font = systemFontOfPX(40);
    NSAttributedString *secrectPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入密码" attributes:@{NSFontAttributeName :systemFontOfPX(40),NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#bfcfe5"]}];
    self.secrectTextField.attributedPlaceholder = secrectPlaceholder;
    
    
    [self.plateNumTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.viewThree.mas_centerY);
        make.height.mas_equalTo(kHeightOfPt(80));
        make.left.mas_equalTo(self.viewThree.mas_left).offset(kWidthOfPt(30 + 80 + 40 + 150));
        make.right.mas_equalTo(self.viewThree.mas_right).offset(- kWidthOfPt(160));
    }];
    self.plateNumTextField.font = systemFontOfPX(40);
    NSAttributedString *plateNumPlaceHolder = [[NSAttributedString alloc]initWithString:@"请输入车牌号" attributes:@{NSFontAttributeName :systemFontOfPX(40),NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#bfcfe5"]}];
    self.plateNumTextField.attributedPlaceholder = plateNumPlaceHolder;
    
    [self.scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kWidthOfPt(160));
        make.height.mas_equalTo(self.viewThree.mas_height);
        make.centerY.mas_equalTo(self.viewThree.mas_centerY);
        make.right.mas_equalTo(self.viewThree.mas_right);
    }];
    self.scanButton.layer.cornerRadius = kHeightOfPt(55);
    self.plateNumTextField.clipsToBounds = YES;
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(kWidthOfPt(820));
        make.height.mas_equalTo(kHeightOfPt(120));
        make.top.mas_equalTo(self.viewThree.mas_bottom).offset(kHeightOfPt(120));
    }];
    self.loginButton.layer.cornerRadius = kHeightOfPt(55);
    self.loginButton.titleLabel.font = systemFontOfPX(50);
    
    [self.fogetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kWidthOfPt(180));
        make.top.mas_equalTo(self.viewThree.mas_bottom).offset(kHeightOfPt(20));
        make.width.mas_equalTo(kWidthOfPt(230));
        make.height.mas_equalTo(kHeightOfPt(50));
    }];
    self.fogetButton.titleLabel.font = systemFontOfPX(40);
    
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kWidthOfPt(180));
        make.top.mas_equalTo(self.viewThree.mas_bottom).offset(kHeightOfPt(20));
        make.width.mas_equalTo(kWidthOfPt(230));
        make.height.mas_equalTo(kHeightOfPt(50));
    }];
    self.registerButton.titleLabel.font = systemFontOfPX(40);
    
    //    [self.changePassWordButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.view.mas_centerX);
//        make.height.mas_equalTo(kHeightOfPt(40));
//        make.width.mas_equalTo(kWidthOfPt(240));
//        make.bottom.mas_equalTo(self.view.mas_bottom).offset( - kHeightOfPt(40));
//    }];
//    self.changePassWordButton.titleLabel.font = systemFontOfPX(40);
    
    
    if ( [[NSUserDefaults standardUserDefaults]valueForKey:@"USER_ACOOUNT"]) {
        self.userAcoountTextField.text = [[NSUserDefaults standardUserDefaults]valueForKey:@"USER_ACOOUNT"];
    }
    if ([[NSUserDefaults standardUserDefaults]valueForKey:@"PLANTE_Num"]) {
        NSString *planteNum = [[NSUserDefaults standardUserDefaults]valueForKey:@"PLANTE_Num"];
        self.plateNumTextField.text = [planteNum substringFromIndex:1];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.userAcoountTextField resignFirstResponder];
    [self.plateNumTextField resignFirstResponder];
    [self.secrectTextField resignFirstResponder];
    [self.pullView hiddenPullList];
    
}

#pragma cagra

- (void)addCAGradient
{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.view.bounds;
    UIColor *color1 = [UIColor colorWithHexString:@"#87c122"];
    UIColor *color2 = [UIColor colorWithHexString:@"#09aa3a"];
    gradientLayer.colors = @[(id)color1.CGColor,(id)color2.CGColor];
    [self.view.layer insertSublayer:gradientLayer atIndex:0];
    
    UIColor *lineColor1 = [UIColor colorWithHexString:@"#ffffff" alpha:0];
    UIColor *lineColor2 = [UIColor colorWithHexString:@"#ffffff" alpha:0.5];
    UIColor *lineColor3 = [UIColor colorWithHexString:@"#ffffff" alpha:1];
    CAGradientLayer *leftLine = [CAGradientLayer layer];
    leftLine.frame = CGRectMake(0, kScreenHeight - kHeightOfPt(60), kWidthOfPt(420), kHeightOfPt(4));
    leftLine.colors = @[(id)lineColor1.CGColor,(id)lineColor2.CGColor,(id)lineColor3.CGColor];
    leftLine.locations = @[@0,@0.7,@1];
    leftLine.startPoint = CGPointMake(0, 0.5);
    leftLine.endPoint = CGPointMake(1, 0.5);
    [self.view.layer addSublayer:leftLine];
    
    CAGradientLayer *rightLine = [CAGradientLayer layer];
    rightLine.frame = CGRectMake(kScreenWidth - kWidthOfPt(420), kScreenHeight - kHeightOfPt(60), kWidthOfPt(420), kHeightOfPt(4));
    rightLine.colors = @[(id)lineColor1.CGColor,(id)lineColor2.CGColor,(id)lineColor3.CGColor];
    rightLine.locations = @[@0,@0.7,@1];
    rightLine.startPoint = CGPointMake(1, 0.5);
    rightLine.endPoint = CGPointMake(0, 0.5);
    [self.view.layer addSublayer:rightLine];

}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}


- (IBAction)scan {
    AVAuthorizationStatus authStatus=[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus==1||authStatus==2) {
        UIAlertView* av=[[UIAlertView alloc]initWithTitle:@"请到设置－隐私中打开相机访问权限" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [av show];
    }else{
        RootViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"RootViewController" ];
        @weakify(self)
        vc.planteBlock = ^(NSString *jsonStr){
        @strongify(self)
            NSData *strData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:strData options:0 error:nil];
            NSString *planteNum = [jsonDic objectForKey:@"plate"];
            self.pullView.label.text = [planteNum substringWithRange:NSMakeRange(0, 1)];
            self.plateNumTextField.text = [planteNum substringFromIndex:1];
        };

        [self.navigationController pushViewController:vc animated:YES];
        [self.userAcoountTextField resignFirstResponder];
        [self.plateNumTextField resignFirstResponder];
        [self.secrectTextField resignFirstResponder];
        [self.pullView hiddenPullList];
    }
}

//- (IBAction)registerButtonAction:(id)sender {
//    RegisterViewController *registerVc = [RegisterViewController new];
//    
//    [self.navigationController pushViewController:registerVc animated:YES];
//}


@end
